package com.jsbj.framework.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
//映射webSocket服务路径
@ServerEndpoint("/api/webSocket/{userId}")
@Component
public class MyWebSocket {

    private String userId;

    private Session session;

    private static Map<String,MyWebSocket> client = new ConcurrentHashMap<>();

    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet();

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session){
        log.info("新连接：{}",userId);
        if (!isEmpty(userId)){
            this.userId = userId;
            this.session = session;
            client.put(userId, this);
            log.info("现在连接的客户编码为：" + userId);

            //加入set中
            webSocketSet.add(this);
            log.error("webSocketSetall{}",webSocketSet.size());
            for (MyWebSocket item : webSocketSet) {
                log.error("webSocketSetitem{}",item.userId);
            }
        }
    }

    /**
     * 关闭时执行
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);

        log.info("连接：{} 关闭", this.userId);
    }

    /**
     * 收到消息时执行
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到用户{}的消息:{}", this.userId, message);
//        for (MyWebSocket item : webSocketSet) {
//            //这里可以设定只推送给这个equCode的，为null则全部推送
//            if (item.userId.equals(userId)) {
//                item.sendMessage(message);
//            }
//        }
        //回复用户
//        session.getAsyncRemote().sendText("收到 " + this.userId + " 的消息:" + message);
    }

    /**
     * 连接错误时执行
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("用户id为：{}的连接发送错误", this.userId);
        error.printStackTrace();
    }

    /**
     * 消息点对点推送
     * @param message
     */
    public void sendMessageToUser(String userId,String message) {

        for (MyWebSocket item : webSocketSet) {
            //这里可以设定只推送给这个equCode的，为null则全部推送
            if (item.userId.equals(userId)) {
                log.error("MyWebSocket pushMessage:" + userId);
                item.sendMessage(message);
            }
        }

//        MyWebSocket session = client.get(userId);
//        if (session != null) {
//            if (session.session.isOpen()) {
////                session.session.getAsyncRemote().sendText("收到 " + userId + " 的消息:" + message);
//                session.session.getAsyncRemote().sendText("收到一条待办信息:" + message);
//            } else {
//                log.info("用户session关闭");
//            }
//        } else {
//            log.info("用户session不存在");
//        }
    }

    public void sendMessage(String message){
        this.session.getAsyncRemote().sendText(message);

    }

    private static boolean isEmpty(String s) {
        return s == null || s.length() == 0 || "".equals(s)
                || "null".equalsIgnoreCase(s)
                || "undefined".equalsIgnoreCase(s);
    }

}

